<?php
/* 
 * Copyright (C) 2010 Emanuele Colonnelli <emanuele.colonnelli@phpstruct.org>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace org\phpstruct\core;
use org\phpstruct\util;

/**
 * Description of View
 *
 * @author Emanuele Colonnelli <emanuele.colonnelli@phpstruct.org>
 */
class View {

    public static function load(){

        $base = sprintf('%s%sview',$_SERVER['DOCUMENT_ROOT'],\DIRECTORY_SEPARATOR);

        $protocol = 'http';
        if(preg_match('/https/',strtolower($_SERVER['SERVER_PROTOCOL']))){
            $protocol = 'https';
        }

        $url = "{$protocol}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

        $path = \parse_url($_SERVER['REQUEST_URI'],\PHP_URL_PATH);

        $f2load = util\StdLib::normalizePath(sprintf('%s%s',$base,$path));

        if(is_dir($f2load)){
            $main = sprintf('%s%smain.php',$f2load,\DIRECTORY_SEPARATOR);
            if(\file_exists($main)){
                require_once $main;
            } else {
                throw new \Exception(Error::E_LOADER_FILENOTFOUND(), Error::E_LOADER_FILENOTFOUND, null);
            }
        } else if (\is_file ("{$f2load}.php")){

            if(!\is_readable("{$f2load}.php")){
                throw new \Exception(Error::E_LOADER_FILENOTFOUND(), Error::E_LOADER_FILENOTFOUND, null);
            }

            if(\file_exists("{$f2load}.php")){
                require_once "{$f2load}.php";
            } else {
                throw new \Exception(Error::E_LOADER_FILENOTFOUND(), Error::E_LOADER_FILENOTFOUND, null);
            }
        } else {
//            die('NOT FOUND: ' . "{$f2load}.php");
            util\Navigator::errorPage(util\NavigationErrors::NOT_FOUND);
        }
    }

}

